package com.dhecp.project.logstics.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.logstics.domain.FbaBoxDetail;
import com.dhecp.project.logstics.domain.FbaDevanning;
import com.dhecp.project.logstics.domain.FbaDevanningDetail;
import com.dhecp.project.logstics.domain.FbaDispatch;
import com.dhecp.project.logstics.mapper.FbaBoxDetailMapper;
import com.dhecp.project.logstics.mapper.FbaDevanningDetailMapper;
import com.dhecp.project.logstics.mapper.FbaDevanningMapper;
import com.dhecp.project.logstics.mapper.FbaDispatchDetailMapper;
import com.dhecp.project.logstics.mapper.FbaDispatchMapper;
import com.dhecp.project.logstics.service.FbaDispatchService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 头程计划单 服务层
 * @Author fxz
 * @Date 2022/9/23
 */
@Service
public class FbaDispatchServicelmpl extends BaseModuleServiceImpl implements FbaDispatchService {


    @Autowired
    private FbaDispatchMapper fbaDispatchMapper;
    @Autowired
    private FbaDispatchDetailMapper fbaDispatchDetailMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private FbaBoxDetailMapper fbaBoxDetailMapper;

    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private FbaDevanningMapper fbaDevanningMapper;
    @Autowired
    private FbaDevanningDetailMapper fbaDevanningDetailMapper;

    private String moduleTable = ModuleTable.FBA_SPELLTICKET;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;



    /**
     * 查询头程计划单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<FbaDispatch> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句

        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "code asc";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }

        return fbaDispatchMapper.select(params);
    }
//
//
//    /**
//     * 查询头程计划单
//     * @param params
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public List<FbaBoxDetail> querySonList(Map<String, Object> params) {
//        return fbaBoxDetailMapper.queryList(params);
//    }
//
//
//    /**
//     * 新增头程计划单
//     * @param params
//     * @return
//     */
//    @Override
//    public AjaxResult insertFbaBox(Map<String, Object> params) {
//        if (StringUtils.isEmpty(params)) {
//            return AjaxResult.error("数据提交失败，必填参数有误！");
//        }
//
//        FbaBox entity = JSON.parseObject(JSON.toJSONString(params), FbaBox.class);
//        entity.setGuid(RandomValueUtils.getGUID());
//        entity.setCreateUser(ShiroUtils.getUserId());
//        entity.setCreateTime(new Date());
//        entity.setUpdateUser(ShiroUtils.getUserId());
//        entity.setUpdateTime(new Date());
//        if (entity.getGuid() == null || "".equals(entity.getGuid())){
//            entity.setGuid(RandomValueUtils.getGUID());
//        }
//
//        if (entity.getCode() == null || entity.getCode().length() == 0) {
//            return AjaxResult.error("数据提交失败，必填参数有误！");
//        }
//
//        fbaBoxMapper.insertFbaBox(entity);
//        return AjaxResult.success("操作成功");
//    }
//
    @Override
    public FbaDispatch queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return fbaDispatchMapper.selectFirstRecordByNid(params);
    }

    /**
     *@Description: 保存
     *@Param: [params] moduleTable 必要参数：功能唯一标识
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
        if (params.get("infoMap") == null || params.get("infoMap") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack.infomap"));
        }
        FbaDispatch fbaDispatch = JSON.parseObject(params.get("infoMap").toString(), FbaDispatch.class);
        fbaDispatch.setUpdateTime(new Date());
        //修改发货详情
        fbaDispatchMapper.updateByGuid(fbaDispatch);
        //返回id用于前端查询
        String resGuid = fbaDispatch.getGuid();

        List<FbaBoxDetail> fbaBoxDetailList = JSON.parseArray(params.get("infoItems").toString(), FbaBoxDetail.class);
        List<FbaBoxDetail> repeat = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("箱重(kg)")).collect(Collectors.toList());
        List<FbaBoxDetail> casesGaugeLength = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("箱规长(cm)")).collect(Collectors.toList());
        List<FbaBoxDetail> tankGaugeWide = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("箱规宽(cm)")).collect(Collectors.toList());
        List<FbaBoxDetail> boxGaugeHigh = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("箱规高(cm)")).collect(Collectors.toList());
        List<FbaBoxDetail> toss = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("抛重(kg)")).collect(Collectors.toList());
        List<FbaBoxDetail> pPprice = fbaBoxDetailList.stream().filter(fbaBoxDetail2 -> fbaBoxDetail2.getSerial().equals("商品采购价(￡)")).collect(Collectors.toList());
        List<FbaBoxDetail> fbaBoxDetailListNew = new ArrayList<>();
        FbaBoxDetail fbaBoxDetailNew;
        //删除装箱详情数据
        fbaBoxDetailMapper.delete(fbaDispatch.getCodePlanOrder());
        for (int i = 0; i < fbaBoxDetailList.size(); i++) {
            // 排除箱重、箱规、抛重数据
            if (!fbaBoxDetailList.get(i).getScrapData().equals("1")) {
                for (int j = 0; j < 10; j++) {
//                    if (fbaBoxDetailList.get(i).getTheFirstCase() != null || !fbaBoxDetailList.get(i).getTheFirstCase().equals("")) {
                    fbaBoxDetailNew = new FbaBoxDetail();
                    //优先不考虑字段是否有填写
                    fbaBoxDetailNew.setGuid(RandomValueUtils.getGUID());
                    //关联头程计划详情
                    fbaBoxDetailNew.setProductInfo("");
                    //计划详情的id
                    fbaBoxDetailNew.setCode(fbaBoxDetailList.get(i).getCode());
                    fbaBoxDetailNew.setCodeBox(fbaDispatch.getCodeBox());
                    fbaBoxDetailNew.setCodeShipment(fbaDispatch.getCodePlanOrder());
                    fbaBoxDetailNew.setBoxIndex(j);
                    fbaBoxDetailNew.setBUser(ShiroUtils.getMandatorId());
                    fbaBoxDetailNew.setBDept(ShiroUtils.getMandatorDeptPath());
                    fbaBoxDetailNew.setDeleted(0);
                    fbaBoxDetailNew.setCreateTime(new Date());
                    fbaBoxDetailNew.setCreateUser(ShiroUtils.getMandatorId());

                    switch (j) {
                        case 0:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheFirstCase(),
                                    casesGaugeLength.get(0).getTheFirstCase(), tankGaugeWide.get(0).getTheFirstCase(), boxGaugeHigh.get(0).getTheFirstCase(),
                                    toss.get(0).getTheFirstCase(),fbaBoxDetailList.get(i).getTheFirstCase(),pPprice.get(0).getTheFirstCase());
                            break;
                        case 1:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheSecondCase(),
                                    casesGaugeLength.get(0).getTheSecondCase(), tankGaugeWide.get(0).getTheSecondCase(), boxGaugeHigh.get(0).getTheSecondCase(),
                                    toss.get(0).getTheSecondCase(),fbaBoxDetailList.get(i).getTheSecondCase(),pPprice.get(0).getTheSecondCase());
                            break;
                        case 2:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheThirdCase(),
                                    casesGaugeLength.get(0).getTheThirdCase(), tankGaugeWide.get(0).getTheThirdCase(), boxGaugeHigh.get(0).getTheThirdCase(),
                                    toss.get(0).getTheThirdCase(),fbaBoxDetailList.get(i).getTheThirdCase(),pPprice.get(0).getTheThirdCase());
                            break;
                        case 3:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheFourCase(),
                                    casesGaugeLength.get(0).getTheFourCase(), tankGaugeWide.get(0).getTheFourCase(), boxGaugeHigh.get(0).getTheFourCase(),
                                    toss.get(0).getTheFourCase(),fbaBoxDetailList.get(i).getTheFourCase(),pPprice.get(0).getTheFourCase());
                            break;
                        case 4:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheFiveCase(),
                                    casesGaugeLength.get(0).getTheFiveCase(), tankGaugeWide.get(0).getTheFiveCase(), boxGaugeHigh.get(0).getTheFiveCase(),
                                    toss.get(0).getTheFiveCase(),fbaBoxDetailList.get(i).getTheFiveCase(),pPprice.get(0).getTheFiveCase());
                            break;
                        case 5:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheFixCase(),
                                    casesGaugeLength.get(0).getTheFixCase(), tankGaugeWide.get(0).getTheFixCase(), boxGaugeHigh.get(0).getTheFixCase(),
                                    toss.get(0).getTheFixCase(),fbaBoxDetailList.get(i).getTheFixCase(),pPprice.get(0).getTheFixCase());
                            break;
                        case 6:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheSevenCase(),
                                    casesGaugeLength.get(0).getTheSevenCase(), tankGaugeWide.get(0).getTheSevenCase(), boxGaugeHigh.get(0).getTheSevenCase(),
                                    toss.get(0).getTheSevenCase(),fbaBoxDetailList.get(i).getTheSevenCase(),pPprice.get(0).getTheSevenCase());
                            break;
                        case 7:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheEightCase(),
                                    casesGaugeLength.get(0).getTheEightCase(), tankGaugeWide.get(0).getTheEightCase(), boxGaugeHigh.get(0).getTheEightCase(),
                                    toss.get(0).getTheEightCase(),fbaBoxDetailList.get(i).getTheEightCase(),pPprice.get(0).getTheEightCase());
                            break;
                        case 8:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheNineCase(),
                                    casesGaugeLength.get(0).getTheNineCase(), tankGaugeWide.get(0).getTheNineCase(), boxGaugeHigh.get(0).getTheNineCase(),
                                    toss.get(0).getTheNineCase(),fbaBoxDetailList.get(i).getTheNineCase(),pPprice.get(0).getTheNineCase());
                            break;
                        case 9:
                            valuation(fbaBoxDetailNew, fbaBoxDetailListNew, repeat.get(0).getTheTenCase(),
                                    casesGaugeLength.get(0).getTheTenCase(), tankGaugeWide.get(0).getTheTenCase(), boxGaugeHigh.get(0).getTheTenCase(),
                                    toss.get(0).getTheTenCase(),fbaBoxDetailList.get(i).getTheTenCase(),pPprice.get(0).getTheTenCase());
                            break;
                    }
//                    }
                }
            }
        }
        fbaBoxDetailMapper.batchInsert(fbaBoxDetailListNew);
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resGuid);
    }

    /**
     *  给对应的箱子赋值
     * @param fbaBoxDetailNew  箱子详情对象
     * @param fbaBoxDetailListNew 箱子详情数组
     * @param weight 箱重
     * @param length 长度
     * @param width 宽度
     * @param height 高度
     * @param weightVol  抛重
     * @return
     */
    private List<FbaBoxDetail> valuation(FbaBoxDetail fbaBoxDetailNew,
                                         List<FbaBoxDetail> fbaBoxDetailListNew,String weight,
                                         String length,String width,String height,String weightVol,String boxNum,String purchasePrice){
        fbaBoxDetailNew.setWeight(weight);
        fbaBoxDetailNew.setLength(length);
        fbaBoxDetailNew.setWidth(width);
        fbaBoxDetailNew.setHeight(height);
        fbaBoxDetailNew.setWeightVol(weightVol);
        fbaBoxDetailNew.setPurchasePrice(purchasePrice);
        fbaBoxDetailNew.setBoxNum(boxNum);
        fbaBoxDetailListNew.add(fbaBoxDetailNew);
        return fbaBoxDetailListNew;
    }

    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        List<FbaDispatch> fbaDispatchList =  JSON.parseArray(params.get("infoItems").toString(), FbaDispatch.class);
        for (FbaDispatch item:fbaDispatchList
        ) {
            //修改头程发货状态
            item.setUpdateTime(new Date());
            item.setState(params.get("state").toString());
            item.setAuditTime(new Date());
            item.setAuditUser(ShiroUtils.getUserId());
            fbaDispatchMapper.update(item);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        FbaDispatch fbaDispatch = new FbaDispatch();
        fbaDispatch.setGuid(params.get("guid").toString());
        fbaDispatch.setState(params.get("state").toString());
        fbaDispatch.setUpdateTime(new Date());
        fbaDispatch.setAuditUser("");
        fbaDispatch.setAuditTime(null);
        fbaDispatchMapper.update(fbaDispatch);
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     *@Description: 拆箱动作- 修改发货状态、并且新增拆箱单
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult devanningPost(Map<String, Object> params) {
        List<FbaDispatch> fbaDispatchList =  JSON.parseArray(params.get("infoItems").toString(), FbaDispatch.class);
        FbaDevanning fbaDevanning;
        FbaDevanningDetail fbaDevanningDetail;
        for (FbaDispatch item:fbaDispatchList
        ) {
            //修改头程发货状态
            item.setUpdateTime(new Date());
            item.setState(params.get("state").toString());
            item.setAuditTime(new Date());
            item.setAuditUser(ShiroUtils.getUserId());
            fbaDispatchMapper.update(item);

            params.put("moduleTable", params.get("moduleTable").toString());
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
            //新增拆箱单数据
            fbaDevanning= new FbaDevanning();
            fbaDevanning.setCodeBox(item.getCodeBox());
            fbaDevanning.setCodePlanOrder(item.getCodePlanOrder());
            fbaDevanning.setCodeDevanning(moduleNidAndBid.getBid());
            fbaDevanning.setCodeDispatch(item.getCode());
            fbaDevanning.setCodeCompany(item.getCodeCompany());
            fbaDevanning.setNameCompany(item.getNameCompany());
            fbaDevanning.setRemark(params.get("remark").toString());
            fbaDevanning.setState("0");
            fbaDevanning.setCreateUser(ShiroUtils.getUserId());
            fbaDevanning.setCreateTime(new Date());
            fbaDevanning.setGuid(RandomValueUtils.getGUID());
            fbaDevanning.setIid(0);
            fbaDevanning.setNid(moduleNidAndBid.getNid());
            fbaDevanning.setBid(moduleNidAndBid.getBid());
            fbaDevanning.setCid(ShiroUtils.getMandatorCid());
            fbaDevanning.setCidName(ShiroUtils.getMandatorCidName());
            fbaDevanning.setbUser(ShiroUtils.getMandatorId());
            fbaDevanning.setbUserName(ShiroUtils.getMandatorName());
            fbaDevanning.setbDept(ShiroUtils.getMandatorDeptPath());
            fbaDevanning.setbDeptName(ShiroUtils.getMandatorDeptName());
            fbaDevanning.setbPosition(ShiroUtils.getMandatorPositionNameDa());
            fbaDevanning.setaUser(ShiroUtils.getUserId());
            fbaDevanning.setaUserName(ShiroUtils.getUserName());
            fbaDevanning.setaDept(ShiroUtils.getUserDeptPath());
            fbaDevanning.setaDeptName(ShiroUtils.getUserDeptName());
            fbaDevanning.setaPosition(ShiroUtils.getUserPositionNameDa());
            fbaDevanning.setCreateTime(new Date());
            fbaDevanning.setEffectStock(false);
            fbaDevanning.setDeleted(false);
            fbaDevanningMapper.insertFbaDevanning(fbaDevanning);

            //获取当前装箱单有多少头程订单
            params.put("codePlanOrder",fbaDevanning.getCodePlanOrder());
            List<FbaBoxDetail> queryList = fbaBoxDetailMapper.select(params);
            for (FbaBoxDetail fbaBoxDetail : queryList){
                //新增拆单详情
                fbaDevanningDetail = new FbaDevanningDetail();
                fbaDevanningDetail.setGuid(RandomValueUtils.getGUID());
                fbaDevanningDetail.setCodeDevanning(fbaDevanning.getCodeDevanning());
                fbaDevanningDetail.setCommodityCode(fbaBoxDetail.getCommodityCode());
                fbaDevanningDetail.setNameGoodsCn(fbaBoxDetail.getNameGoodsCn());
                fbaDevanningDetail.setNumPlanDeliver(fbaBoxDetail.getNumPlanDeliver());
                fbaDevanningDetail.setCreateUser(ShiroUtils.getUserId());
                fbaDevanningDetail.setCreateTime(new Date());
                fbaDevanningDetailMapper.insertFbaDevanningDetail(fbaDevanningDetail);
            }

        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
}
